﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using PleaseORM.Extensions;
using PleaseORM.Interfaces;

namespace PleaseORM
{
	public class Save
	{
		protected IPlease _please { get; set; }

		public Save(IPlease please)
		{
			_please = please;
		}

		public void This(dynamic entity)
		{
			IEnumerable<string> members = entity.GetDynamicMemberNames();
			var fields = new StringBuilder();
			var parameters = new StringBuilder();
			string entityName = entity.GetType().Name;
			
			SqlCommand command = new SqlCommand();

			for (int i = 0; i < members.Count(); i++)
			{
				if (!members.ElementAt(i).Equals("Id"))
				{
					var field = members.ElementAt(i);
					var parameter = string.Format("@{0}", field.ToLower());
					var value = entity.GetValue(field);

					fields.Append(field).Append(", ");
					parameters.Append(parameter).Append(", ");

					command.Parameters.Add(parameter, value);
				}
			}

			var queryInsert = "INSERT INTO {0} ({1}) VALUES ({2});SELECT SCOPE_IDENTITY();"
				.Change(entityName.MakePlural(), fields.ToString(0, fields.Length - 2), parameters.ToString(0, parameters.Length - 2));
			command.CommandText = queryInsert;

			var identity = _please.Configuration.Database.ExecuteReader(command);
			identity.Read();

			entity.Id = Convert.ToInt32(identity[0]);
		}


	}
}
